#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>
#include <QNetworkInterface>
#include "../Common/common.h"
#include "server.h"
#include <QDateTime>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->editIP->setText(GetLocalIP());
    ui->editPort->setText(QString::number(serverPort));

    connect(Server::getInstance(), &Server::sigLog, this, &Widget::AddLog);
}

Widget::~Widget()
{
    delete ui;
}

QString Widget::GetLocalIP()
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach(QHostAddress address, list) {
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            return address.toString();
        }
    }
    return "";
}

void Widget::AddLog(QString text)
{
    QString strTime = QDateTime::currentDateTime().toString("[yyyy/MM/dd HH:mm:ss]");
    ui->listWidget->addItem(strTime + " " + text);
}

void Widget::on_btnStart_clicked()
{
    bool bOK = false;
    int port = ui->editPort->text().toInt(&bOK);
    if (bOK) {
        if (Server::getInstance()->Start(port)) {
            //使用 QStringLiteral 宏可以在编译期把代码里的常量字符串 str 直接构造为 QString 对象，于是运行时就不再需要额外的构造开销了。
            AddLog(QStringLiteral("服务器启动成功！端口：%1").arg(port));
        }
        else {
            AddLog(QStringLiteral("服务器启动失败！端口: %1").arg(port));
        }
    }
    else {
        AddLog(QStringLiteral("请输入正确的端口号！"));
    }
}

